package com.tudou.ppjoke.utils;

import android.content.res.AssetManager;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tudou.libcommon.AppGlobals;
import com.tudou.ppjoke.model.BottomBar;
import com.tudou.ppjoke.model.Destination;
import com.tudou.ppjoke.model.SofaTab;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

public
class AppConfig {

    private static HashMap<String, Destination> sDestConfig;
    private static BottomBar sBottomBar;
    private static SofaTab sSofaTab, sFindTabConfig;

    public static HashMap<String, Destination> getsDestConfig(){
        if (sDestConfig==null){
            if (sDestConfig==null){
                String content = pareseFile("destination.json");
                Log.i("--temp", "getsDestConfig: "+content);
                sDestConfig = JSON.parseObject(content, new TypeReference<HashMap<String, Destination>>() {
                }.getType());
                Log.i("--temp", "getsDestConfig: "+sDestConfig.toString());
            }
        }

        return sDestConfig;
    }

    public static BottomBar getsBottomBar(){
        if (sBottomBar==null){
            String content=pareseFile("main_tabs_config.json");
            sBottomBar=JSON.parseObject(content,BottomBar.class);
        }

        return sBottomBar;
    }

    public static SofaTab getSofaTabConfig(){
        if (sSofaTab == null) {
            String content = pareseFile("sofa_tabs_config.json");
            sSofaTab = JSON.parseObject(content, SofaTab.class);
            Collections.sort(sSofaTab.tabs, new Comparator<SofaTab.Tabs>() {
                @Override
                public int compare(SofaTab.Tabs o1, SofaTab.Tabs o2) {
                    return o1.index < o2.index ? -1 : 1;
                }
            });
        }
        return sSofaTab;
    }

    private static String pareseFile(String flieName){
        AssetManager assets = AppGlobals.getApplication().getResources().getAssets();

        InputStream stream=null;
        BufferedReader reader=null;
        StringBuilder builder=new StringBuilder();
        try {
             stream = assets.open(flieName);
             reader=new BufferedReader(new InputStreamReader(stream));
             String line =null;
             while ((line=reader.readLine())!=null){
                builder.append(line);
             }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (stream!=null){
                    stream.close();
                }
                if (reader!=null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return builder.toString();
    }
}
